/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManagedBeans;

import Utilitaires.PropertiesReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;

/**
 *
 * @author michachel
 */
public class NodeManagedBean {

    private int nodeId;
    private String titre;
    private int thematique;

    private Properties properties;
    
    
    
    public void save() throws MalformedURLException, IOException, JSONException
    {
        this.properties = PropertiesReader.getProperties();
        
        URL url = new URL("http://"+properties.getProperty("adress")+":"+properties.getProperty("port")+"/node");
        HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
        connexion.setDoOutput(true);
        connexion.setRequestMethod("PUT");
        
        try
        {
            OutputStreamWriter out = new OutputStreamWriter(connexion.getOutputStream());
            String json = this.generateJson();
            out.write(json);
            out.close();
        }
        catch(Exception e)
        {}
        finally
        {
            System.out.println(connexion.getResponseCode());
            System.out.println(connexion.getResponseMessage());
        }
        System.out.println("ContentBean.save()");
    }
    
     /**
     * Generate JSON from content data
     * @return
     * @throws JSONException 
     */
    public String generateJson() throws JSONException
    {
        JSONObject json = new JSONObject();
        
        // Add objects != String
        json.put("node_id", this.nodeId);
        
        if (this.titre != null) {
            json.put("title", this.titre);
        }
        
        if (this.thematique != 0) {
            json.put("thematic_id", this.thematique);
        }
        
        
        return json.toString();
    }
    public int getNodeId() {
        return nodeId;
    }

    public void setNodeId(int nodeId) {
        this.nodeId = nodeId;
    }

    public String getTitre() {
        return titre;
    }

    public void setTitre(String titre) {
        this.titre = titre;
    }

    public int getThematique() {
        return thematique;
    }

    public void setThematique(int thematique) {
        this.thematique = thematique;
    }

    /**
     * Creates a new instance of NodeManagedBean
     */
    public NodeManagedBean() {
    }
}
